package com.hgl.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**<pre>
 * - 
 * ClassName : com.teach.commons.BeanUtil
 * Author : J.L.Zhou
 * E-Mail : 2233875735@qq.com
 * Date : 2020年7月22日 下午3:41:04
 * Version : 1.0
 * Copyright 2020 jlzhou.top Inc. All rights reserved. 
 * Warning: this content is only for internal circulation of the company. 
 * It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 **/
public class BeanUtil {

	private BeanUtil(){}
	
	public static void copy(Object sourceBean,Object targetBean,String... ignoreProperties){
		Set<String> ignorePropertiesSet = new HashSet<>();
		if(ignoreProperties!=null){
			java.util.Collections.addAll(ignorePropertiesSet, ignoreProperties);
		}
		Class<?> sourceClass = sourceBean.getClass();
		Class<?> targetClass = targetBean.getClass();
		try{
			BeanInfo sourceInfo = Introspector.getBeanInfo(sourceClass);
			PropertyDescriptor[] propertys = sourceInfo.getPropertyDescriptors();
			Map<String, PropertyDescriptor> map = new HashMap<String, PropertyDescriptor>();
			for(PropertyDescriptor p : propertys){
				map.put(p.getName(), p);
			}
			BeanInfo targetInfo = Introspector.getBeanInfo(targetClass);
			propertys = targetInfo.getPropertyDescriptors();
			for(PropertyDescriptor p : propertys){
				if(p.getWriteMethod()==null){//如果目标bean的属性没有setter,跳过，进入下一个属性
					continue;
				}
				if(ignorePropertiesSet.contains(p.getName())){//如果目标bean的属性在忽略的属性中,跳过，进入下一个属性
					continue;
				}
				PropertyDescriptor sourceProperty = map.get(p.getName());
				if(sourceProperty==null || sourceProperty.getReadMethod()==null){//如果原对象没有对应的getter方法,跳过，进入下一个属性
					continue;
				}
				Object obj = sourceProperty.getReadMethod().invoke(sourceBean);
				if(obj!=null){
					p.getWriteMethod().invoke(targetBean, obj);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
}
